package engine

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"sync"
)

type JsonStore struct{
	source map[string]interface{}
	JsonPath string
	once sync.Once
	sync.RWMutex
}

func (t *JsonStore) Set(key string,g interface{}) bool {
	t.Lock()
	defer t.Unlock()
	t.source[key] = g
	return true
}

func (t *JsonStore) Get(id string) interface{} {
	t.RLock()
	defer t.RUnlock()
	v,ok := t.source[id]
	if !ok {
		return nil
	}
	return v
}

func (t *JsonStore) WriteDisk() int {
	t.Lock()
	defer t.Unlock()
	bytes,err := json.MarshalIndent(t.source," "," ")
	if err != nil {
		fmt.Errorf("write Disk of Json MarshalIndex at Error:",err)
	}
	if err := ioutil.WriteFile(t.JsonPath,bytes,0777); err != nil {
		fmt.Errorf("write file at Error:",err)
	}
	return len(t.source)
}

func (t *JsonStore) LoadDisk() bool {
	t.Lock()
	defer t.Unlock()

	bytes,err := ioutil.ReadFile(t.JsonPath)
	t.source = make(map[string]interface{})
	if err != nil {
		fmt.Errorf("加载[%s]数据失败:[%s]",t.JsonPath,err)
		return false
	}
	err = json.Unmarshal(bytes,&t.source)
	if err != nil {
		fmt.Errorf("Read Disk of Json Unmarshal at Error:",err)
	}
	return true
}

func CreateJsonStore(jsonPath string) *JsonStore {
	t := JsonStore{JsonPath:jsonPath}
	t.LoadDisk()
	return &t
}